/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import models.User;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.hibernate.Session;
import service.HibernateUtil;
import service.UserDao;

/**
 *
 * @author Aster
 */
public class ProfileController extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        boolean student = false;
        long userID = 0;
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("status")) {
                if (cookie.getValue().length() > 0) {
                    student = true;
                } 
            }else if (cookie.getName().equals("userID")) {
                userID = Long.parseLong(cookie.getValue());
            }
        }
        if (student == true) {
            HttpSession session = request.getSession(true);
            HibernateUtil HU = new HibernateUtil();
            Session sessie = HU.openSession();

            //stuk om de aangewezen cursussen van docent op te halen
            try {
                UserDao ud = new UserDao(sessie);
                User user = ud.get(userID);//dit moet dynamisch worden
                session.setAttribute("user", user);
                DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String birthDateString = formatter.format(user.getBirthDate());
            System.out.println("birthdate: " + birthDateString);
            request.setAttribute("birthDate", birthDateString);
            } catch (Exception ex) {
                System.out.println(ex);
            }
            /*try {
                //stuk om de deelnemende studenten van de door de docent gekozen cursus te showen
                CourseDao cd = new CourseDao(sessie);
                long d = 2;//dit moet dynamsich worden
                Course course = cd.get(d);
                if (course.getUsers() != null) {
                    session.setAttribute("participants", course.getUsers());
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }*/
            
            Locale list[] = SimpleDateFormat.getAvailableLocales();
            session.setAttribute("countries", list);
            
            forward(request, response);
        } else {
            response.sendRedirect("/");
        }
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            IOException, ServletException {
        //System.out.println("request description: " + request.getParameter("description"));
        //filePath = getServletContext().getRealPath("/") + "files/";
        HibernateUtil HU = new HibernateUtil();
            Session sessie = HU.openSession();
            long userID = 0;
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("userID")) {
                userID = Long.parseLong(cookie.getValue());
            }
        }
        UserDao ud = new UserDao(sessie);
        User user = ud.get(userID);
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
                    if (!item.isFormField()) {
                        String fileName = item.getName();

                        String root = getServletContext().getRealPath("/");
                        File path = new File(root + "/images/profile");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }
                        File uploadedFile = new File(path + "/" + fileName);
                        item.write(uploadedFile);
                        
                        user.setProfilePic(fileName);
                        ud.update(user);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            user.setFirstName(request.getParameter("firstName"));
            user.setLastName(request.getParameter("lastName"));
            user.setCity(request.getParameter("city"));
            user.setZipCode(request.getParameter("zipcode"));
            user.setEmail(request.getParameter("email"));
            user.setAddress(request.getParameter("address"));
            user.setCountry(request.getParameter("country"));
            user.setGender(request.getParameter("gender"));
            ud.update(user);            
        }
        //RequestDispatcher dispatcher = request.getRequestDispatcher("tutorfilemanager.jsp");
        //dispatcher.forward(request, response);
        response.sendRedirect("/profile");
    }
    
    private void forward(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //request.setAttribute("pageTitle", titel);

        String address = "/profile.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
}
